package nuc.zhangchao.test.interceptor;

import nuc.zhangchao.test.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author Zhang Chao
 * @Date 2020/12/29 18:43
 * @Version 1.0
 * 登录的拦截器()
 */
public class LoginInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //逻辑：判断用户是否登录  本质：判断session中有没有user
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("login");
//        System.out.println("user信息已经放到了session中了"+user);
        if(user==null){
            //没有登录(重定向)
            //response.sendRedirect(request.getContextPath()+"/login");
            request.setAttribute("msg","没有权限，请先登录");
            request.getRequestDispatcher("/login").forward(request,response);
            //不放行
            return false;
        }else{
            //放行  访问目标资源
            return true;
        }

    }
}
